﻿using RpcCentral.Collect.Model;
using RpcCentral.Common;
using RpcCentral.DAL;
using RpcCentral.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace RpcCentral.Collect.Controller
{
    public class RpcServerConfigController : DataSyncClass
    {
        public RpcServerConfigController (long rpcMerId, long sysTypeId)
        {
            this.RpcMerId = rpcMerId;
            this.SystemTypeId = sysTypeId;
        }

        public long RpcMerId
        {
            get;
        }

        public long SystemTypeId
        {
            get;
        }
        public RpcServiceConfig[] Server { get; private set; }
        /// <summary>
        /// 是否启用区域隔离
        /// </summary>
        public bool IsRegionIsolate { get; private set; }
        /// <summary>
        /// 隔离级别
        /// </summary>
        public bool IsolateLevel { get; private set; }
        public int Ver { get; private set; } = 0;

        public BalancedType BalancedType { get; private set; }

        protected override void SyncData ()
        {
            using (IocScope scope = UnityHelper.CreateScore())
            {
                RemoteConfig[] list = scope.Resolve<IServerGroupCollect>().GetRemoteServer(this.RpcMerId, this.SystemTypeId);
                if (!list.IsNull())
                {
                    BasicServer[] servers = scope.Resolve<IRemoteServerDAL>().GetRemoteServerConfig(list.ConvertAll(a => a.ServerId));
                    this.Server = servers.ConvertAll(a =>
                    {
                        return new RpcServiceConfig
                        {
                            RegionId = a.RegionId,
                            ServerId = a.Id,
                            Weight = list.Find(b => b.ServerId == a.Id, b => b.Weight, 1),
                            VerNum = a.VerNum
                        };
                    });
                }
                else
                {
                    this.Server = new RpcServiceConfig[0];
                }
                MerConfig config = scope.Resolve<IRpcMerConfigCollect>().GetConfig(this.RpcMerId, this.SystemTypeId);
                if (config == null)
                {
                    this.IsolateLevel = false;
                    this.IsRegionIsolate = true;
                    this.BalancedType = BalancedType.avg;
                }
                else
                {
                    this.BalancedType = config.BalancedType;
                    this.IsolateLevel = config.IsolateLevel;
                    this.IsRegionIsolate = config.IsRegionIsolate;
                }
                this.Ver = Tools.GetRandom();
            }
        }

    }
}
